$(function() {
    
    $("form").submit(function(){
        var retval = true;
        if ($('#from_date').val() == ""){
            toggleHighlight("#from_date_section", "Please select a date");
            retval = false;
        }
        if ($('#to_date').val() == ""){
            toggleHighlight("#to_date_section", "Please select a date");
            retval = false;
        }
        return retval;
    });
    
    $(".datepick input").focus(function(){
        $(this).blur();
    });
    
    $("#from_date").change(function(){
        toggleHighlight("#from_date_section");
    });
    
    $("#to_date").change(function(){
        toggleHighlight("#to_date_section");
    });

    $('#from_date, #to_date').datepicker({
        showOn: "button",
        beforeShow: customRange,
        dateFormat: "yy-mm-dd",
    });
    
    $('#from_date, #to_date').next("button").click(function(){
        $("#preset_interval").val('C');
    });
    
    $("#from_date").change(function(){
        $('#to_date').val("");
    });
    
    $("#preset_interval").change(function(){
        var from_date = "";
        var to_date = "";
        var to_object = new Date();
        var opt = $(this).val();
        
        if (opt == '1W'){
            to_object.setDate(to_object.getDate()+6);
        }
        else if (opt == '2W'){
            to_object.setDate(to_object.getDate()+13);
        }
        else if (opt == '3W'){
            to_object.setDate(to_object.getDate()+20);
        }
        else if (opt == '1M'){
            to_object.setMonth(to_object.getMonth()+1);
        }
        else if (opt == '2M'){
            to_object.setMonth(to_object.getMonth()+2);
        }
        else if (opt == '3M'){
            to_object.setMonth(to_object.getMonth()+3);
        }
        
        if (opt != 'C'){
            from_date = $.datepicker.formatDate('yy-mm-dd', new Date());
            to_date = $.datepicker.formatDate('yy-mm-dd', to_object);
        }
        
        toggleHighlight("#to_date_section");
        toggleHighlight("#from_date_section");
        
        $("#from_date").val(from_date);
        $("#to_date").val(to_date);
    });

});

function customRange(input) {
    if ($('#from_date').val() != ""){
        if (input.id == 'to_date') {
            var minDate = new Date($('#from_date').val());

            minDate.setDate(minDate.getDate());

            return {
                minDate: minDate
            };
        }
    }
    
    return {minDate: new Date()}
    
}
